import BaseSprite from "../../../Script/Base/BaseSprite";
import { IHospitalCellData } from "../../../Script/Interface/IMessage";
import HospitalIcon from "./HospitalIcon";
import HospitalUI from "./HospitalUI";

const { ccclass, property } = cc._decorator;

@ccclass
export default class HospitalGroup extends BaseSprite {

    @property({ type: cc.Node, tooltip: "icon预制体" })
    private itemIcon: cc.Node = null;

    private itemNodes: cc.Node[][] = [];
    private itemDatas: IHospitalCellData[] = [];
    private groupId: number = 0;

    public setData(gid: number) {
        this.groupId = gid;
        this.itemNodes = [];
        this.itemDatas = HospitalUI.instance.getItemDataByGid(gid);

        // 目前组中顺序是左右中, 为了组中生成两个时中间空着
        const data = HospitalUI.instance.data;
        if (data.col > 2) {
            this.node.children[0].zIndex = 0;
            this.node.children[1].zIndex = 2;
            this.node.children[2].zIndex = 1;
        }

        for (let i = 0; i < this.itemDatas.length; i++) {
            let temp = [];
            for (let k = 0; k < 2; k++) {
                const parent = this.node.children[i];
                const node = cc.instantiate(this.itemIcon);
                node.parent = parent;
                node.x = (k - 1) * 10;
                node.y += k * 10;
                temp.push(node);
            }
            this.itemNodes.push(temp);

            this.refresh(i);
        }
    }

    public refresh(col: number, isMove: boolean = false) {
        const tempData = this.itemDatas.find((o1) => o1.col === col);
        this.itemNodes[col].forEach((o, i) => {            
            o.active = true;
            if (tempData.curDeep + i >= tempData.mids.length) {
                o.active = false;
                return;
            }

            if (isMove) {
                o.x = (i - 1) * 10;
                o.y = 20 * i;
                o.stopAllActions();
                if (i === 0) {
                    cc.tween(o).sequence(
                        cc.moveTo(0, cc.v2(o.x, o.y + 20)),
                        cc.moveTo(0.3, cc.v2(o.x, o.y)).easing(cc.easeBackInOut()),
                    ).start();
                } else {
                    cc.tween(o).sequence(
                        cc.fadeOut(0),
                        cc.fadeIn(0.3),
                    ).start();
                }
            }
            o.zIndex = this.itemNodes[col].length - i;
            o.getComponent(HospitalIcon).setItemData(tempData, i);
        });
    }

    public getItemNodes() {
        return this.itemNodes;
    }

    public shakeTip(id: number) {
        this.itemNodes.forEach((o1)=>{
            o1.forEach((o2)=>{
                o2.getComponent(HospitalIcon).shakeTip(id);
            });
        });
    }
}